﻿$(function () {
    $("body").addClass(localStorage.getItem('config-skin'));
    $("[data-toggle='tooltip']").tooltip();
})

$.reload = function () {
    location.reload();
    return false;
}
$.loading = function (bool, text) {
    var $loadingpage = top.$("#loadingPage");
    var $loadingtext = $loadingpage.find('.loading-content');
    if (bool) {
        $loadingpage.show();
    } else {
        if ($loadingtext.attr('istableloading') == undefined) {
            $loadingpage.hide();
        }
    }
    if (text) {
        $loadingtext.html(text);
    } else {
        $loadingtext.html("数据加载中，请稍后…");
    }
    $loadingtext.css("left", (top.$('body').width() - $loadingtext.width()) / 2 - 50);
    $loadingtext.css("top", (top.$('body').height() - $loadingtext.height()) / 2);
}

$.request = function (name) {
    var search = location.search.slice(1);
    var arr = search.split("&");
    for (var i = 0; i < arr.length; i++) {
        var ar = arr[i].split("=");
        if (ar[0] == name) {
            if (unescape(ar[1]) == 'undefined') {
                return "";
            } else {
                return unescape(ar[1]);
            }
        }
    }
    return "";
}
$.currentWindow = function () {
    var iframeId = top.$(".Djy_iframe:visible").attr("id");
    return top.frames[iframeId];
}
$.browser = function () {
    var userAgent = navigator.userAgent;
    var isOpera = userAgent.indexOf("Opera") > -1;
    if (isOpera) {
        return "Opera";
    }

    if (userAgent.indexOf("Firefox") > -1) {
        return "FF";
    }
    if (userAgent.indexOf("Chrome") > -1) {
        if (window.navigator.webkitPersistentStorage.toString().indexOf('DeprecatedStorageQuota') > -1) {
            return "Chrome";
        } else {
            return "360";
        }
    }
    if (userAgent.indexOf("Safari") > -1) {
        return "Safari";
    }
    if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
        return "IE";
    }
}

$.modalOpen = function (options) {
    var config = $.extend({
        id: null,
        title: '系统窗口',
        width: "100px",
        height: "100px",
        url: '',
        type: 2,
        shade: 0.3,
        btn: ['确认', '关闭'],
        btnclass: ['btn btn-primary', 'btn btn-danger'],
        callBack: function () {
            return true;
        },
        success: null
    }, options);

    var _width = Math.min(top.$(window).width(), parseInt(config.width)) + 'px';
    var _height = Math.min(top.$(window).height(),parseInt(config.height)) + 'px';

    var option = {
        id: config.id,
        type: config.type,
        shade: config.shade,
        title: config.title,
        fix: false,
        area: [_width, _height],
        content: config.url,
        btn: config.btn,
        btnclass: config.btnclass,
        success: config.success,
        yes: function (index) {
            config.callBack(config.id, index);
        }
        , cancel: function () {
            return true;
        }
    };

    //扩展3个按钮的时候
    if (config.handlers) {
        option = $.extend(option, config.handlers);
    }
    top.layer.open(option);
}

$.modalConfirm = function (content, callBack) {
    top.layer.confirm(content, {
        icon: "fa-exclamation-circle",
        title: "系统提示",
        btn: ['确认', '取消'],
        btnclass: ['btn btn-primary', 'btn btn-danger'],
    }, function (index) {
        callBack(true, index);
    }, function (index) {
        callBack(false, index);
    });
}
$.modalAlert = function (content, type) {
    var icon = "";
    if (type == 'success') {
        icon = "fa-check-circle";
    }
    if (type == 'error') {
        icon = "fa-times-circle";
    }
    if (type == 'warning') {
        icon = "fa-exclamation-circle";
    }
    top.layer.alert(content, {
        icon: icon,
        title: "系统提示",
        btn: ['确认'],
        btnclass: ['btn btn-primary'],
    });
}
$.modalMsg = function (content, type) {
    if (type != undefined) {
        var icon = "";
        if (type == 'success') {
            icon = "fa-check-circle";
        }
        if (type == 'error') {
            icon = "fa-times-circle";
        }
        if (type == 'warning') {
            icon = "fa-exclamation-circle";
        }
        top.layer.msg(content, { icon: icon, time: 3000, shift: 5 });
        top.$(".layui-layer-msg").find('i.' + icon).parents('.layui-layer-msg').addClass('layui-layer-msg-' + type);
    } else {
        top.layer.msg(content);
    }
}
$.modalClose = function () {
    var index = top.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    var $IsdialogClose = top.$("#layui-layer" + index).find('.layui-layer-btn').find("#IsdialogClose");
    var IsClose = $IsdialogClose.is(":checked");
    if ($IsdialogClose.length == 0) {
        IsClose = true;
    }
    if (IsClose) {
        top.layer.close(index);
    } else {
        location.reload();
    }
}
$.submitForm = function (options) {
    var config = $.extend({
        url: "",
        param: [],
        loading: "正在提交数据...",
        success: null,
        close: true,
        complete: function () {
            $.loading(false);
        }
    }, options);

    if (config.param && typeof(config.param) != "string" && $('[name=__RequestVerificationToken]').length > 0) {
        config.param["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
    }

    var option = {
        url: config.url,
        data: config.param,
        type: "post",
        dataType: "json",
        success: function (data) {
            $.loading(false);
            if (data.state == "success") {
                config.success(data);
                if (data.message) {
                    $.modalMsg(data.message, data.state);
                }
                if (config.close == true) {
                    $.modalClose();
                }
            }
            else if (data.state == "error" && data.message == "NOT_LOGIN") {
                top.window.location.href = "/Login/Index?url=" + location.href;
                return false;
            }
            else {
                $.modalAlert(data.message, data.state);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $.loading(false);
            $.modalMsg(errorThrown, "error");
        },
        beforeSend: function () {
            $.loading(true, config.loading);
        },
        complete: config.complete
    };

    if (config.extra) {
        option = $.extend(option, config.extra);
    }
    $.ajax(option);
}

$.deleteForm = function (options) {
    var config = $.extend({
        prompt: "注：您确定要删除该项数据吗？",
        url: "",
        param: [],
        loading: "正在删除数据...",
        success: null,
        close: true
    }, options);

    if ($('[name=__RequestVerificationToken]').length > 0) {
        config.param["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
    }
    $.modalConfirm(config.prompt, function (r) {
        if (r) {
            $.loading(true, config.loading);
            window.setTimeout(function () {
                $.ajax({
                    url: config.url,
                    data: config.param,
                    type: "post",
                    dataType: "json",
                    success: function (data) {
                        if (data.state == "success") {
                            config.success(data);
                            $.modalMsg(data.message, data.state);
                        } else {
                            $.modalAlert(data.message, data.state);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.loading(false);
                        $.modalMsg(errorThrown, "error");
                    },
                    beforeSend: function () {
                        $.loading(true, config.loading);
                    },
                    complete: function () {
                        $.loading(false);
                    }
                });
            }, 500);
        }
    });
}

$.jsonWhere = function (data, action) {
    if (action == null) return;
    var reval = new Array();
    $(data).each(function (i, v) {
        if (action(v)) {
            reval.push(v);
        }
    })
    return reval;
}
$.fn.jqGridRowValue = function () {
    var $grid = $(this), rows = $grid.rows;
    var selectedRowIds = $grid.jqGrid("getGridParam", "selarrrow");
    if (selectedRowIds != "") {
        var json = [];
        var len = selectedRowIds.length;
        for (var i = 0; i < len; i++) {
            var rowData = $grid.jqGrid('getRowData', selectedRowIds[i]);
            json.push(rowData);
        }
        return json;
    } else {
        selectedRowIds = $grid.jqGrid('getGridParam', 'selrow');
        if (selectedRowIds) {
            return $grid.jqGrid('getRowData', selectedRowIds);
        }
        else {
            return [];
        }
    }
}
$.fn.formValid = function () {
    return $(this).valid({
        errorPlacement: function (error, element) {
            element.parents('.formValue').addClass('has-error');
            element.parents('.has-error').find('i.error').remove();
            element.parents('.has-error').append('<i class="form-control-feedback fa fa-exclamation-circle error" data-placement="left" data-toggle="tooltip" title="' + error + '"></i>');
            $("[data-toggle='tooltip']").tooltip();
            if (element.parents('.input-group').hasClass('input-group')) {
                element.parents('.has-error').find('i.error').css('right', '33px');
            }
        },
        success: function (element) {
            element.parents('.has-error').removeClass('has-error').find('i.error').remove();
        }
    });
}
$.fn.formSerialize = function (formData) {
    var element = $(this);
    if (formData) {
        for (var key in formData) {
            var $id = element.find('#' + key);
            if ($id.length == 0) {
                continue;
            }
            var value = formData[key];//$.trim(formData[key]).replace(/&nbsp;/g, '');
            var type = $id.attr('type');
            if ($id.hasClass("select2-hidden-accessible")) {
                type = "select";
            }
            switch (type) {
                case "checkbox":
                case "radio":
                    $id.prop("checked", value === true || value == "true");
                    break;
                case "select":
                    $id.val(value).trigger("change");
                    break;
                default:
                    $id.val(value);
                    break;
            }
        }
        return element;
    }

    formData = {};
    element.find('input,select,textarea').each(function (r) {
        var $this = $(this);
        var id = $this.attr('id');
        if (!id) {
            return;
        }
        var type = $this.attr('type');
        switch (type) {
            case "checkbox":
            case "radio":
                formData[id] = $this.prop("checked");
                break;
            default:
                formData[id] = $this.val();
                break;
        }
    });
    if ($('[name=__RequestVerificationToken]').length > 0) {
        formData["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
    }
    return formData;
};
$.fn.renderSelect = function (options) {
    var config = $.extend({
        id: "id",
        text: "text",
        search: false,
        url: "",
        param: [],
        change: null,
        minimumResultsForSearch: -1,
        tags: false
    }, options);
    $(this).select2(config);
    return $(this);
};

$.fn.dataGrid = function (options) {
    var config = $.extend({
        datatype: "json",
        autowidth: true,
        rownumbers: true,
        shrinkToFit: false,
        gridview: true,
        onSelectRow: function (rowid) {
            var $operate = $(".operate");
            if ($operate.length == 0)
                return;
            var length = $(this).jqGrid("getGridParam", "selrow").length;
            if (length > 0) {
                $operate.animate({ "left": 0 }, 200);
            } else {
                $operate.animate({ "left": '-100.1%' }, 200);
            }        }
    }, options);
    $(this).jqGrid(config);
    var $operate = $(".operate");
    if ($operate.length == 0)
        return;
    $operate.find('.close').click(function () {
        $operate.animate({ "left": '-100.1%' }, 200);
    });
};

$.getStyle = function(obj, attr) {
    if (obj.currentStyle) {
        return obj.currentStyle[attr];  //只适用于IE
    }
    else {
        return getComputedStyle(obj, false)[attr];   //只适用于FF,Chrome,Safa
    }
}

$.GetDivToBodyOffsetX = function(obj, intX) {
    if (obj.parentElement) {
        intX += obj.parentElement.offsetLeft;
        intX = $.GetDivToBodyOffsetX(obj.parentElement, intX);
    }
    return intX;
}

$.GetDivToBodyOffsetY = function(obj, intY) {
    if (obj.parentElement) {
        intY += obj.parentElement.offsetTop;
        intY = $.GetDivToBodyOffsetY(obj.parentElement, intY);
    }
    return intY;
}

$.intersectWith = function (el, region) {
    var s_top = parseInt(el.style.top);
    var s_left = parseInt(el.style.left);
    var s_right = s_left + parseInt(el.offsetWidth);
    var s_bottom = s_top + parseInt(el.offsetHeight);

    var r_top = parseInt(region.offsetTop);
    var r_left = parseInt(region.offsetLeft);
    var r_right = r_left + parseInt(region.offsetWidth);
    var r_bottom = r_top + parseInt(region.offsetHeight);

    var t = Math.max(s_top, r_top);
    var r = Math.min(s_right, r_right);
    var b = Math.min(s_bottom, r_bottom);
    var l = Math.max(s_left, r_left);

    return (b > t + 5 && r > l + 5) ? region : null;
}